package com.karaoke.android.kege.vm

import android.databinding.Bindable
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.databinding.adapters.ViewBindingAdapter
import android.inputmethodservice.KeyboardView
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.TextView
import com.apkfuns.logutils.LogUtils
import com.karaoke.android.kege.*
import com.karaoke.android.kege.fragment.HandWriteFragment
import com.karaoke.android.kege.fragment.KeywordBoardFragment
import com.karaoke.android.kege.fragment.SearchContents
import com.karaoke.android.kege.fragment.SearchFragment
import com.karaoke.android.library.mvvm.FragmentViewModel
import com.wwengine.hw.PaintView
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import universum.studios.android.fragment.manage.FragmentController
import universum.studios.android.fragment.manage.FragmentRequest
import kotlin.properties.Delegates

/**
 * Created by allen on 2017/4/23.
 */
class SearchViewModel(private val f: SearchFragment) : FragmentViewModel()
{
    init
    {
        EventBus.getDefault().register(this)
    }

    //    private var keywordController by Delegates.notNull<FragmentController>()
    private var contentController by Delegates.notNull<FragmentController>()
    val keyboard = R.xml.pinyin
    val textBinding = ObservableField<String>()
    var searchText by Delegates.observable("") {
        _, old, new ->
        textBinding.set(new)
        LogUtils.e("search text new $new old $old")
        if (old != new)
            EventBus.getDefault().post(OnSearchTextChangedEvent(new))
    }
    private var checkId = 0
    override fun onDestroy()
    {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @Bindable
    var charArray = CharArray(8)
    var selectIndex = inputType
    val cleanHwBoard = ObservableBoolean()
    val hwListener: PaintView.OnResultListener = PaintView.OnResultListener { result ->
        charArray = result
        notifyPropertyChanged(com.karaoke.android.kege.BR.charArray)
    }

    //拼音
    var isCanDelete: ObservableBoolean = ObservableBoolean()

    init
    {
//        keywordController = FragmentController(f.childFragmentManager)
//        keywordController.viewContainerId = R.id.keyboardContainer
        contentController = FragmentController(f.childFragmentManager)
//        contentController.viewContainerId = R.id.searchContent
        contentController.factory = SearchContents()
    }


    /*
    清除手写板
     */
    fun hwClean()
    {
        EventBus.getDefault().post(ResetHwBoardEvent())
    }

    /**
     * 手写板选中单字
     */
    fun hwSelected(v: View)
    {
        val textView = v as TextView
        if (!textView.text.toString().isNullOrBlank())
        {
            searchText += textView.text
            hwClean()
        }
    }

    fun onDelete()
    {
        if (searchText.isNotEmpty())
            searchText = searchText.substring(IntRange(0, searchText.length - 2))
    }

    fun onClear()
    {
        searchText = ""
    }


    @Subscriber
    fun onSearchTypeChanged(e: SearchTypeChangedEvent)
    {
        searchText = e.text
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
    }

    fun tabOnCompletedChanged(group: RadioGroup, checkId: Int)
    {
        if (group.id == R.id.langTab)
        {
            when (checkId)
            {
                R.id.rbPinYIn  ->
                {
                    inputType = InputType.PIN_YIN
                    contentController.newRequest(KeywordBoardFragment.newInstance(this))
                            .tag("PIN_YIN")
                            .viewContainerId(R.id.keyboardContainer)
                            .transaction(FragmentRequest.REPLACE)
                            .execute()
                }
                R.id.rbShowXie ->
                {
                    inputType = InputType.SHOW_XIE
                    contentController.newRequest(HandWriteFragment.newInstance(this))
                            .viewContainerId(R.id.keyboardContainer)
                            .transaction(FragmentRequest.REPLACE)
                            .tag("SHOW_XIE")
                            .execute()
                }
            }
        }
        else
        {
            var f = 0
            when (checkId)
            {
                R.id.rbAll    -> f = SearchContents.ALL
                R.id.rbSong   -> f = SearchContents.SONG
                R.id.rbSinger -> f = SearchContents.SINGER
            }
            if (this.checkId != checkId)
                contentController.newRequest(f)
                        .viewContainerId(R.id.searchContent)
                        .transaction(FragmentRequest.REPLACE)
                        .tag("page_$checkId")
                        .execute()
            this.checkId = checkId
        }
    }

    val onKeyboardActionListener = object : KeyboardView.OnKeyboardActionListener
    {
        override fun swipeRight()
        {
        }

        override fun onPress(primaryCode: Int)
        {
        }

        override fun onRelease(primaryCode: Int)
        {
        }

        override fun swipeLeft()
        {
        }

        override fun swipeUp()
        {
        }

        override fun swipeDown()
        {
        }

        override fun onKey(primaryCode: Int, keyCodes: IntArray?)
        {
            val s = Character.toString(primaryCode.toChar())
            searchText += s
        }

        override fun onText(text: CharSequence?)
        {
        }
    }

    val onViewAttachedToWindow = ViewBindingAdapter.OnViewAttachedToWindow {
        if (it.id == R.id.textInput)
        {
            (it as EditText).inputType = android.text.InputType.TYPE_NULL
        }
    }


}